package com.clothing.customization.service.impl;

import com.clothing.customization.entity.DesignerQualification;
import com.clothing.customization.entity.DesignerSchedule;
import com.clothing.customization.repository.DesignerQualificationRepository;
import com.clothing.customization.repository.DesignerScheduleRepository;
import com.clothing.customization.service.DesignerManagementService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 设计师管理服务实现类
 */
@Service
@RequiredArgsConstructor
public class DesignerManagementServiceImpl implements DesignerManagementService {

    private final DesignerQualificationRepository qualificationRepository;
    private final DesignerScheduleRepository scheduleRepository;

    // ==================== 资质审核与信息维护相关方法 ====================

    @Override
    @Transactional(readOnly = true)
    public Page<DesignerQualification> getQualificationList(Map<String, Object> params) {
        String designerName = (String) params.get("designerName");
        Integer status = params.get("status") != null ? Integer.parseInt(params.get("status").toString()) : null;
        
        int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 0;
        int size = params.get("size") != null ? Integer.parseInt(params.get("size").toString()) : 10;
        String sortBy = (String) params.getOrDefault("sortBy", "createTime");
        String direction = (String) params.getOrDefault("direction", "DESC");
        
        Sort sort = Sort.by(Sort.Direction.fromString(direction), sortBy);
        Pageable pageable = PageRequest.of(page, size, sort);
        
        // 使用简化版本的查询方法
        return qualificationRepository.findByConditions(designerName, status, pageable);
    }

    @Override
    @Transactional(readOnly = true)
    public DesignerQualification getQualificationById(Long id) {
        return qualificationRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("资质不存在"));
    }

    @Override
    @Transactional
    public boolean auditQualification(Long id, Integer status, String auditRemark, Long auditorId) {
        DesignerQualification qualification = qualificationRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("资质不存在"));
        
        qualification.setStatus(status);
        qualification.setRemark(auditRemark);
        qualification.setReviewerId(auditorId);
        qualification.setReviewTime(new Date());
        
        qualificationRepository.save(qualification);
        return true;
    }

    @Override
    @Transactional(readOnly = true)
    public Map<Integer, Long> countQualificationByStatus() {
        List<Object[]> statusCounts = qualificationRepository.countByStatusGroup();
        Map<Integer, Long> result = new HashMap<>();
        
        // 初始化默认值
        result.put(0, 0L); // 待审核
        result.put(1, 0L); // 已通过
        result.put(2, 0L); // 已拒绝
        
        // 填充实际统计值
        for (Object[] count : statusCounts) {
            if (count[0] != null && count[1] != null) {
                Integer status = (Integer) count[0];
                Long countValue = ((Number) count[1]).longValue();
                result.put(status, countValue);
            }
        }
        
        return result;
    }

    // ==================== 日程管理相关方法 ====================

    @Override
    @Transactional(readOnly = true)
    public Page<DesignerSchedule> getScheduleList(Map<String, Object> params) {
        Long designerId = params.get("designerId") != null ? Long.parseLong(params.get("designerId").toString()) : null;
        String scheduleType = (String) params.get("scheduleType");
        Integer status = params.get("status") != null ? Integer.parseInt(params.get("status").toString()) : null;
        
        Date startTime = null;
        Date endTime = null;
        if (params.get("startTime") != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                startTime = sdf.parse(params.get("startTime").toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (params.get("endTime") != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                endTime = sdf.parse(params.get("endTime").toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        
        int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 0;
        int size = params.get("size") != null ? Integer.parseInt(params.get("size").toString()) : 10;
        
        PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "startTime"));
        
        return scheduleRepository.findByConditions(designerId, scheduleType, status, startTime, endTime, pageRequest);
    }

    @Override
    @Transactional(readOnly = true)
    public DesignerSchedule getScheduleById(Long id) {
        return scheduleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("日程不存在"));
    }

    @Override
    @Transactional
    public DesignerSchedule addSchedule(DesignerSchedule schedule) {
        // 验证日程时间
        if (schedule.getStartTime().after(schedule.getEndTime())) {
            throw new RuntimeException("开始时间不能晚于结束时间");
        }
        
        // 检查时间冲突
        List<DesignerSchedule> conflictSchedules = scheduleRepository.findConflictSchedules(
            schedule.getDesignerId(), schedule.getStartTime(), schedule.getEndTime());
        
        if (!conflictSchedules.isEmpty()) {
            throw new RuntimeException("日程时间与已有日程冲突");
        }
        
        return scheduleRepository.save(schedule);
    }

    @Override
    @Transactional
    public DesignerSchedule updateSchedule(DesignerSchedule schedule) {
        // 验证日程是否存在
        DesignerSchedule existingSchedule = scheduleRepository.findById(schedule.getId())
                .orElseThrow(() -> new RuntimeException("日程不存在"));
        
        // 验证日程状态
        if (existingSchedule.getStatus() == 2 || existingSchedule.getStatus() == 3) {
            throw new RuntimeException("已完成或已取消的日程不能修改");
        }
        
        // 更新日程信息
        existingSchedule.setTitle(schedule.getTitle());
        existingSchedule.setDescription(schedule.getDescription());
        existingSchedule.setScheduleDate(schedule.getScheduleDate());
        existingSchedule.setStartTime(schedule.getStartTime());
        existingSchedule.setEndTime(schedule.getEndTime());
        existingSchedule.setLocation(schedule.getLocation());
        existingSchedule.setScheduleType(schedule.getScheduleType());
        existingSchedule.setStatus(schedule.getStatus());
        
        // 如果状态变更为已完成，记录完成时间
        if (schedule.getStatus() == 2 && existingSchedule.getStatus() != 2) {
            existingSchedule.setCompleteTime(new Date());
        }
        
        return scheduleRepository.save(existingSchedule);
    }

    @Override
    @Transactional
    public boolean deleteSchedule(Long id) {
        // 验证日程是否存在
        DesignerSchedule schedule = scheduleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("日程不存在"));
        
        // 验证日程状态
        if (schedule.getStatus() == 1) {
            throw new RuntimeException("进行中的日程不能删除");
        }
        
        scheduleRepository.deleteById(id);
        return true;
    }

    @Override
    @Transactional(readOnly = true)
    public boolean checkScheduleConflict(Long designerId, Date startTime, Date endTime, Long excludeId) {
        List<DesignerSchedule> conflictSchedules = scheduleRepository.findConflictSchedules(designerId, startTime, endTime);
        
        if (excludeId != null) {
            // 排除当前正在编辑的日程
            conflictSchedules = conflictSchedules.stream()
                    .filter(schedule -> !schedule.getId().equals(excludeId))
                    .collect(Collectors.toList());
        }
        
        return !conflictSchedules.isEmpty();
    }

    @Override
    @Transactional(readOnly = true)
    public List<DesignerSchedule> getDesignerScheduleByTimeRange(Long designerId, Date startTime, Date endTime) {
        return scheduleRepository.findByDesignerIdAndStartTimeBetweenOrderByStartTimeAsc(designerId, startTime, endTime);
    }

    @Override
    @Transactional(readOnly = true)
    public Map<Integer, Long> countScheduleByType(Long designerId) {
        List<Object[]> typeCounts = scheduleRepository.countByScheduleTypeGroup(designerId);
        Map<Integer, Long> result = new HashMap<>();
        
        // 将字符串类型的日程类型转换为数字类型，方便前端处理
        for (Object[] count : typeCounts) {
            if (count[0] != null && count[1] != null) {
                String type = (String) count[0];
                Long countValue = ((Number) count[1]).longValue();
                
                // 按照日程类型映射为数字
                if ("APPOINTMENT".equals(type)) {
                    result.put(1, countValue); // 预约
                } else if ("MEETING".equals(type)) {
                    result.put(2, countValue); // 会议
                } else if ("REST".equals(type)) {
                    result.put(3, countValue); // 休息
                } else {
                    result.put(0, countValue); // 其他
                }
            }
        }
        
        return result;
    }
} 